package online.heycm.platform.web.common.filter.wrapper;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import online.heycm.platform.web.common.filter.RequestHelper;

/**
 * 缓存请求体，可重复读请求，不支持文件上传
 *
 * @author heycm
 * @since 2023/12/9 17:11
 */
public class CacheRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    private Map<String, String> extHeader;

    public CacheRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body = RequestHelper.copyBody(request);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        return new ServletInputStream() {

            private final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(body)));
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if (value == null && extHeader != null) {
            value = extHeader.get(name);
        }
        return value;
    }

    public void addHeader(String name, String value) {
        if (extHeader == null) {
            extHeader = new HashMap<>();
        }
        extHeader.put(name, value);
    }

    public byte[] getBody() {
        return body;
    }

    public boolean isPost() {
        return "POST".equalsIgnoreCase(getMethod());
    }

}
